<?php

namespace backend\models;

use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\LibraryBook;

/**
 * LibraryBookSearch represents the model behind the search form of `backend\models\LibraryBook`.
 */
class LibraryBookSearch extends LibraryBook
{
    public $yearStart;
    public $yearEnd;

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['id', 'year', 'condition_id', 'collection_id', 'bbk_id', 'udk_id'], 'integer'],
            [['author', 'title', 'annotation', 'yearStart', 'yearEnd', 'keywords', 'inventory_number', 'publisher'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        $attributeLabels = parent::attributeLabels();
        $attributeLabels['yearStart'] = 'Год (с)';
        $attributeLabels['yearEnd'] = 'Год (по)';
        return $attributeLabels;
    }

    /**
     * {@inheritdoc}
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = LibraryBook::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'year' => $this->year,
            'condition_id' => $this->condition_id,
            'collection_id' => $this->collection_id,
            'bbk_id' => $this->bbk_id,
            'udk_id' => $this->udk_id,
        ]);

        $query->andFilterWhere(['like', 'author', $this->author])
            ->andFilterWhere(['like', 'title', $this->title])
            ->andFilterWhere(['like', 'inventory_number', $this->inventory_number])
            ->andFilterWhere(['like', 'annotation', $this->annotation])
            ->andFilterWhere(['like', 'keywords', $this->keywords])
            ->andFilterWhere(['like', 'publisher', $this->publisher])
            ->andFilterWhere(['<=', 'year', $this->yearEnd])
            ->andFilterWhere(['>=', 'year', $this->yearStart]);

        return $dataProvider;
    }
}
